package com.zx.springcloud.controller;



import com.zx.springcloud.entity.Payment;
import com.zx.springcloud.service.PaymentService;
import com.zx.springcloud.vo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ZX
 * @date 2021/3/2
 */
@RestController
@RequestMapping(value = "/payment")
@Slf4j
public class PaymentController
{

    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    String port;
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/create")
    public CommonResult create(Payment payment)
    {
        int result = paymentService.insert(payment);
        log.info("插入结果:" + result);

        return  new CommonResult(200,"成功",result);
    }

    @GetMapping(value = "/get/{id}")
    public  CommonResult getPayment(@PathVariable Long id){

        Payment payment = paymentService.getPaymentById(id);
        System.out.println(1);
        return  new CommonResult(200,"success,端口号："+port,payment);
    }

    @GetMapping("/discovery")
    public  Object discovery(){

        //.getServices() 获取对外暴露的微服务名称。 也就是eureka页面的Instances - Application
        List<String> list = discoveryClient.getServices();
        for (String element : list)
        {
            log.info("****element"+element);
        }
        //.getInstances 获取一个微服务 名称下面的 全部具体实例。
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        for (ServiceInstance instance : instances)
        {
         log.info("***instance"+instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return  this.discoveryClient;
    }

    /**
     * 用来测试Ribbon 自定的负载均衡算法
     * @return
     */
    @GetMapping(value = "/lb")
    public  String getPayment(){
        return  port;
    }

    /**
     * 测试 OpenFeign 的默认连接超时 （默认 1秒钟）
     * @return
     */
    @GetMapping(value = "/timeOut")
    public  String timeOut(){

        try
        {
            TimeUnit.SECONDS.sleep(3);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

         return port;
    }

}
